package cn.jd.basic.interceptor;

import cn.jd.basic.anno.PreAuthorize;
import cn.jd.basic.jwt.JwtUtils;
import cn.jd.basic.jwt.Payload;
import cn.jd.basic.jwt.RsaUtils;
import cn.jd.basic.jwt.UserInfo;
import cn.jd.system.mapper.PermissionMapper;
import cn.jd.user.domain.Logininfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token信息
        String token = request.getHeader("token");
        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 判断key是否存在
        if(!StringUtils.isEmpty(token)){
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            Logininfo logininfo = userInfo.getLogininfo();
          /*  // 获取value
            Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);*/
            // 判断是否存在
            if(logininfo!=null){
                if(logininfo.getType()==0){
                  /*  // 后台成员判断权限
                    HandlerMethod method=(HandlerMethod)handler;
                    // 获取方法注解
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    // 获取方法里面的sn
                    String sn = annotation.sn();*/
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 从方法对象中的到指定注解
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (null != preAuthorize){
                        // 获取注解里面的sn
                        String sn = preAuthorize.sn();
                        // 查询当前用户的权限
                     /*   List<String> snList=permissionMapper.logininfoId(logininfo.getId());*/
                        List<String> snList = userInfo.getPermissions();

//                        snList.forEach(System.out::println);
                        System.out.println(snList);
                        System.out.println(!snList.contains(sn));
                        if(! snList.contains(sn)){
                            // 不在集合里
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }

                    }

                }
                // 重置时间
              /*  redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);*/
                return true;
            }

        }
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
   /* @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token信息
        String token = request.getHeader("token");
        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 判断key是否存在
        if(!StringUtils.isEmpty(token)){
            // 获取value
            Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);
            // 判断是否存在
            if(logininfo!=null){
                if(logininfo.getType()==0){
                  *//*  // 后台成员判断权限
                    HandlerMethod method=(HandlerMethod)handler;
                    // 获取方法注解
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    // 获取方法里面的sn
                    String sn = annotation.sn();*//*
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 从方法对象中的到指定注解
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (null != preAuthorize){
                        // 获取注解里面的sn
                        String sn = preAuthorize.sn();
                        // 查询当前用户的权限
                        List<String> snList=permissionMapper.logininfoId(logininfo.getId());
//                        snList.forEach(System.out::println);
                        System.out.println(snList);
                        System.out.println(!snList.contains(sn));
                        if(! snList.contains(sn)){
                            // 不在集合里
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }

                    }

                }
                // 重置时间
                redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);
                return true;
            }

        }
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }*/


}

